﻿using System;
using System.Security.Principal;
using System.Web;
using EPiServer.Personalization.VisitorGroups;

namespace CriteriaPack.TimeOnSiteCriterion
{
    [VisitorGroupCriterion(
        Category = "Time and Place Criteria",
        Description = "Matches the total length of a user's visit",
        DisplayName = "Time on Site")]
    public class TimeOnSiteCriterion : CriterionBase<TimeOnSiteModel>
    {
        private TimeOnSiteService Service { get; set; }

        public TimeOnSiteCriterion()
        {
            Service = new TimeOnSiteService();
        }

        public override bool IsMatch(IPrincipal principal, HttpContextBase httpContext)
        {
            double secondsToMatch = Service.SecondsToMatch(httpContext, Model.Id.ExternalId);
            return !(secondsToMatch > 0);
        }

        public override void Subscribe(ICriterionEvents criterionEvents)
        {
            criterionEvents.StartSession += criterionEvents_StartSession;
        }

        public override void Unsubscribe(ICriterionEvents criterionEvents)
        {
            criterionEvents.StartSession -= criterionEvents_StartSession;
        }

        public const string SessionStartTimeKey = "SessionStartTime";
       
        public void criterionEvents_StartSession(object sender, CriterionEventArgs e)
        {
            if (e.HttpContext == null)
                return;

            if (e.HttpContext.Session == null)
                return;

            e.HttpContext.Session[SessionStartTimeKey] = DateTime.Now;
        }
    }


}